#include <SPI.h>
#include <Wire.h>
#include <RF24.h>

RF24 ReceiveRadio(10, 9); // CE: D10, CSN: D9

// 定义传输协议
const uint8_t HEADER = 0xAA;
const uint8_t TYPE_PIN_STATE = 0x01; // 引脚状态类型
const uint8_t TYPE_STRING = 0x02;    // 字符串类型

// 定义地址数组（全局变量）
const byte address[5] = {0xF0, 0xF0, 0xF0, 0xF0, 0x66};

// 字节数组用于存储接收到的帧
uint8_t buffer[32];

void setup() {
  Serial.begin(115200);

  ReceiveRadio.begin();
  ReceiveRadio.setAddressWidth(5);
  ReceiveRadio.openReadingPipe(1, address); // 使用全局地址数组
  ReceiveRadio.setChannel(115);        // 通道115
  ReceiveRadio.setPALevel(RF24_PA_LOW);// 低功率
  ReceiveRadio.setDataRate(RF24_1MBPS);// 数据速率1Mbps
  ReceiveRadio.startListening();       // 开始接收
  Serial.println("Receiver initialized.");
}

void processFrame(uint8_t* data, uint8_t length) {
  if (data[0] != HEADER) {
    Serial.print(data[0]);
    Serial.println(" is Invalid frame header.");
    return; // 非法帧，丢弃
  }

  uint8_t payloadLength = data[1]; // 获取数据长度
  if (payloadLength > 29 || length != 32) {
    Serial.println("Invalid frame length.");
    return; // 长度不匹配，丢弃
  }

  uint8_t type = data[2]; // 获取数据类型
  if (type == TYPE_PIN_STATE) {
    Serial.print("Pin States: ");
    for (uint8_t i = 0; i < payloadLength - 1; i++) {
      Serial.print(data[3 + i]);
      Serial.print(" ");
    }
    Serial.println();
  } else if (type == TYPE_STRING) {
    Serial.print("Received String: ");
    for (uint8_t i = 0; i < payloadLength - 1; i++) {
      Serial.print((char)data[3 + i]);
    }
    Serial.println();
  } else {
    Serial.println("Unknown data type.");
  }
}

void loop() {
  if (ReceiveRadio.available()) {
    uint8_t length = ReceiveRadio.getPayloadSize(); // 获取负载大小
    memset(buffer, 0, sizeof(buffer));              // 清空缓冲区
    ReceiveRadio.read(buffer, length);             // 读取数据

    Serial.print("Raw Data: ");
    for (uint8_t i = 0; i < length; i++) {
      Serial.print(buffer[i], HEX);
      Serial.print(" ");
    }
    Serial.println();

    processFrame(buffer, length);                  // 处理数据帧
  }
  delay(10);
}